package com.ask.server.service.impl;

import com.ask.common.enumeration.ActivityStatus;
import com.ask.common.exception.ResourceNotFoundException;
import com.ask.pojo.dto.ActivityDTO;
import com.ask.pojo.entity.Activity;
import com.ask.server.mapper.ActivityMapper;
import com.ask.server.service.IActivityService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.ask.common.constant.ExceptionMessageConstant.RESOURCE_NOTFOUND;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
    /**
     * 新增活动
     * @param activityDTO
     */
    @Override
    public void saveActivity(ActivityDTO activityDTO) {
        // 拷贝前端信息
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityDTO, activity);
        // 额外信息设置
        activity.setCurrentParticipants(0);
        activity.setStatus(ActivityStatus.DRAFT);
        // 存入数据库
        save(activity);
    }

    /**
     * 编辑活动
     * @param activityDTO
     */
    @Override
    public void updateActivity(ActivityDTO activityDTO) {
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityDTO, activity);
        activity.setUpdatedTime(LocalDateTime.now());
        updateById(activity);
    }

    /**
     * 设置活动状态
     * @param id
     * @param status
     */
    @Override
    public void setStatus(Long id, Integer status) {
        // 根绝status获取枚举值
        ActivityStatus activityStatus = ActivityStatus.fromCode(status);
        // 构造跟新条件
        UpdateWrapper<Activity> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id)
                .set("status", activityStatus);
        // 跟新活动状态
        if (!update(wrapper)) {
            throw new ResourceNotFoundException(RESOURCE_NOTFOUND);
        }
    }

    /**
     * 根据id查询活动
     * @param id
     * @return
     */
    @Override
    public Activity queryById(Long id) {
        return getById(id);
    }

    /**
     * 根据分类id查询活动
     * @param categoryId
     * @return
     */
    @Override
    public List<Activity> queryByCategoryId(Long categoryId) {
        List<Activity> activityList = query().eq("category_id", categoryId).list();
        return activityList;
    }
}